package cn.edu.aust.zhuzhang.mydialogtest.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.lang.ref.WeakReference;

import cn.edu.aust.zhuzhang.mydialogtest.MyApplication;
import cn.edu.aust.zhuzhang.mydialogtest.R;
import cn.edu.aust.zhuzhang.mydialogtest.utils.FileTool;

public class Register extends AppCompatActivity {
    private EditText et_username=null;
    private EditText et_password=null;
    private Button btn_regist=null;
    private RadioGroup rg_sex=null;
    private Button btn_sexSelect=null;
    private String sexStr="";
    private static Handler handler=null;
    private int singleSelected=-1;
    private final int[] hobbies={
            R.id.cb_swin,R.id.cb_sing,R.id.cb_music,R.id.cb_book
    };

    private CheckBox[] cb_hobbies=new CheckBox[hobbies.length];
    private final String items[] = { "游泳", "唱歌", "音乐", "读书" };
    private Button btn_hobbySelect=null;
    private String hobStr="";
    private boolean[] hobCheckeds=new boolean[hobbies.length];

    class MyHandler extends Handler{
        WeakReference<Register> actRef;
        MyHandler(Register register){
            this.actRef=new WeakReference<>(register);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String msgStr="";
            if (actRef.get()!=null){
                switch (msg.what){
                    case 1:
                        //更新性别单选按钮组状态
                        if (msg.arg1==0){
                            rg_sex.check(R.id.rb_male);
                            sexStr="male";
                        }else if (msg.arg1==1){
                            rg_sex.check(R.id.rb_female);
                            sexStr="female";
                        }
                        break;
                    case 2:
                        //更新爱好复选框状态
                        Bundle bundle=msg.getData();
                        if (bundle!=null){
                            boolean[] isCheckeds=bundle.getBooleanArray("isCheckeds");
                            for (int i=0;i<isCheckeds.length;i++){
                                cb_hobbies[i].setChecked(isCheckeds[i]);
                            }
                        }

                        break;
                }

            }
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        MyApplication myApplication = (MyApplication) this.getApplicationContext();
        myApplication.topActivity = this;

        handler=new MyHandler(this);

        /*Intent intent=getIntent();
        String unStr=intent.getStringExtra("username");
        Log.i("username",unStr);*/

        et_username=(EditText)findViewById(R.id.et_username);
        et_password=(EditText)findViewById(R.id.et_password);
        btn_regist=(Button)findViewById(R.id.btn_regist);
        rg_sex=(RadioGroup)findViewById(R.id.rg_sex);
        btn_sexSelect=(Button)findViewById(R.id.btn_sexSelect);
        btn_hobbySelect=(Button)findViewById(R.id.btn_hobbySelect);
        for (int i=0;i<hobbies.length;i++){
            CheckBox cb=(CheckBox)findViewById(hobbies[i]);
            cb_hobbies[i]=cb;
            cb.setOnCheckedChangeListener(cbListener);
        }

//        btn_regist.setBackgroundColor(getColor(R.color.regColor));

        /*if (!unStr.equals("")){
            et_username.setText(unStr);
        }*/

        btn_regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username=et_username.getText().toString().trim();
                String pwd=et_password.getText().toString().trim();
                hobStr="";
                for (int i=0;i<hobCheckeds.length;i++){
                    if (hobCheckeds[i]){
                        hobStr+=items[i]+",";
                    }
                }
                if (!hobStr.equals("")){
                    hobStr=hobStr.substring(0,hobStr.length()-1);
                }

                Log.i("hobbies:",hobStr);

                FileTool.writeUserIntoSp(Register.this,username,pwd,sexStr,hobStr);
                Toast.makeText(Register.this,"注册成功！",Toast.LENGTH_LONG).show();

                Intent intent1=new Intent(Register.this, MainActivity.class);
                intent1.putExtra("username",username);
                startActivity(intent1);
                finish();
            }

        });

        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId==R.id.rb_male){
                    sexStr="male";
                    singleSelected=0;
                }else if (checkedId==R.id.rb_female){
                    sexStr="female";
                    singleSelected=1;
                }
            }
        });

        btn_sexSelect.setOnClickListener(listener);
        btn_hobbySelect.setOnClickListener(listener);
    }

    View.OnClickListener listener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //单选对话框
            AlertDialog.Builder builder=new AlertDialog.Builder(Register.this)
                    .setIcon(R.mipmap.ic_launcher);      //设置图标;
            switch (v.getId()){
                case R.id.btn_sexSelect:
                    builder.setTitle("请选择性别：")
                            .setSingleChoiceItems(new String[]{"男", "女"}, singleSelected,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        singleSelected=which;
                                    }
                                })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Message msg= Message.obtain(handler);
                                    msg.what=1;
                                    msg.arg1=singleSelected;
                                    msg.sendToTarget();
                                }
                            });
                    builder.show();
                    break;
                case R.id.btn_hobbySelect:
                    builder.setTitle("请选择爱好：")
                            .setMultiChoiceItems(items,hobCheckeds,new DialogInterface.OnMultiChoiceClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                    if(isChecked){//选项被选取
                                        hobCheckeds[which]=true;
                                    }else {                             //选项被取消
                                        hobCheckeds[which]=false;//从集合中取消
                                    }
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Message msg= Message.obtain(handler);
                                    msg.what=2;
                                    Bundle bundle=new Bundle();
                                    bundle.putBooleanArray("isCheckeds",hobCheckeds);
                                    msg.setData(bundle);
                                    msg.sendToTarget();
                                }
                            });

                    builder.show();
                    break;
            }
        }
    };
    CompoundButton.OnCheckedChangeListener cbListener=new CompoundButton.OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int index=-1;//得到所选的复选框标签
            for (int i=0;i<hobbies.length;i++){
                if (buttonView.getId()==hobbies[i]){
                    index=i;
                    break;
                }
            }

            if(isChecked){//选项被选取
                hobCheckeds[index]=true;
            }else {                             //选项被取消
                hobCheckeds[index]=false;//从集合中取消
            }
        }
    };
}
